<template>
  <section>
    <van-row>
      <van-col>
        <div v-show="!isWatching" class="title">
          <span>连接智温测体温计</span>
        </div>
      </van-col>
    </van-row>
    <van-row>
      <div class="img" v-show="!isWatching" >
        <van-image @click="initManager" width="200" height="110" fit="contain" src="" />
      </div>
    </van-row>
    <van-row>
      <div class="btn">
        <div v-show="!isWatching">
          <span v-if="isSearching"><van-loading color="#1e838b" text-size="14px" size="20px"><span slot="default">{{connectText}}</span></van-loading></span>
          <span v-else>请取出体温计并打开蓝牙</span>
        </div>
        <div v-show="!isWatching">
          <van-button v-show="isSearching" plain :hairline="true" :round="true" size="large" type="info" @click="stopConnect">取消连接</van-button>
          <van-button v-show="!isSearching" plain :hairline="true" :round="true" size="large" type="info" @click="startConnect">开始连接</van-button>
        </div>
        <div v-show="isWatching">
          <van-button plain :hairline="true" :round="true" size="large" type="info" @click="stopMonitor">关闭监控</van-button>
        </div>
      </div>
    </van-row>
  </section>
</template>
<script>
// import "axios"
import "../../util/compatibles";
import common from "../../util/index";
import {apiPostFetch} from "../../util/requests";
import dayjs from "dayjs";

// eslint-disable-next-line no-unused-vars
import {mapState, mapGetters, mapMutations, mapActions} from "vuex";

import {Toast, Button, Row, Col, Image,Loading} from "vant/es";

export default {
  components: {
    [Loading.name]:Loading,
    [Button.name]: Button,
    [Image.name]: Image,
  },
  computed: {
    ...mapState(["isRecording","isWatching","isSearching","isConnected","isScan"]),
  },
  data() {
    return {
      connectText:"正在连接中...",
      title: "bluetooth",
      equipment: [],
      showMaskType: "device",
      servicesData: [],
      characteristicsData: [],
      valueChangeData: {},
      deviceId: null,
      serviceId: null,
      characteristicsId: null,
      ble: null,
      recordInterval:null,
      temperature:null,
    };
  },

  methods: {
    stopConnect(){
      this.setSearchingStatus(0);
      this.stopScan();
      this.disconnect();
    },
    startConnect(){
      this.setSearchingStatus(1);
      this.initManager();
    },
    stopMonitor(){
      console.log("jkgb");
    },
    /**
       * 初始化蓝牙设备
       */
    initManager() {
      //记录开始搜索
      this.ble = api.require("ble");
      // console.log(this.ble);
      this.ble.initManager(res => {
        switch (res.state) {
        case "poweredOn":
          console.log("设备已经打开,初始化成功!");
          this.scan();
          break;
        case "poweredOff":
          console.log("设备已关闭!");
          Toast("请先打开蓝牙设备");
          break;
        case "resetting":
          console.log("正在重置状态");
          break;
        case "unauthorized":
          console.log("设备未授权状态");
          break;
        case "unknown":
          console.log("初始的时候是未知的");
          break;
        case "unsupported":
          console.log("设备不支持的状态");
          break;
        }
      });
    },
    /**
       * 开始搜索蓝牙设备
       */
    scan() {
      this.ble.scan({}, res => {
        if (res.status) {
          console.log("开始扫描");
          this.setScanStatus(1);
          this.getPeripheral();
        }
      },
      );
    },
    /**
       * 停止搜索蓝牙设备
       */
    stopScan() {
      console.log("关闭扫描");
      this.ble.stopScan();
      this.setScanStatus(0);
    },
    /**
       * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
       */
    getPeripheral() {

      this.ble.getPeripheral(res => {
        if (res) {
          if (res.peripherals.length > 0) {
            var wenduDevice = res.peripherals.find(value => value.name === "Temp1");
            if (wenduDevice) {
              this.deviceId = wenduDevice.uuid;
              this.equipment = res.peripherals;
              this.stopScan();
              this.connect(wenduDevice);
            } else {
              this.getPeripheral();
            }
          } else {
            this.getPeripheral();
          }
        } else {
          this.getPeripheral();
        }
      });
    },
    /**
     * 连接低功耗蓝牙
     */
    connect(device) {
      Toast("正在连接设备");
      let deviceId = device.uuid;
      this.ble.connect({peripheralUUID: deviceId}, (res, err) => {
        if (res.status) {
          console.log("连接成功");
          this.setConnetedStatus(1);
          this.discoverService();
        } else {
          console.log("连接失败");
          switch (err.code) {
          case 3:
            console.log("已经连接过了");
            break;
          case 1:
            console.log("uuid为空");
            break;
          case 2:
            console.log("未搜索到该蓝牙设备");
            break;
          case -1:
            console.log("未知错误");
            console.log("开始链接蓝牙设备");
            this.connect(device);
            break;
          }
        }
      });
    },
    /**
       * 断开与低功耗蓝牙设备的连接
       */
    disconnect() {
      let deviceId = this.deviceId;
      this.ble.disconnect({
        peripheralUUID: deviceId,
      }, res => {
        if (res.status) {
          this.setConnetedStatus(0);
          console.log("关闭设备连接");
        }
      });
    },
    /**
       * 获取所有服务
       */
    discoverService() {
      let deviceId = this.deviceId;
      console.log(`开始获取 uuid: ${deviceId} 的服务`);

      this.ble.discoverService({
        peripheralUUID: deviceId,
      }, (res, err) => {
        if (res.status) {
          console.log("已经获取 所有服务");
          this.servicesData = res.services;
          this.serviceId = res.services.find(res => res === "6E400001-B5A3-F393-E0A9-E50E24DCCA9E".toLowerCase());
          this.discoverCharacteristics();
        } else {
          switch (err.code) {
          case 1:
            console.log("uuid为空");
            break;
          case 2:
            console.log("未搜索到该蓝牙设备");
            break;
          case -1:
            console.log("未知错误");
            console.log("开始重新获取服务");
            this.discoverService();
            break;
          }
        }
      });
    },
    /**
       * 获取某个服务下的所有特征值
       */
    discoverCharacteristics() {
      let deviceId = this.deviceId;
      let serviceId = this.serviceId;
      console.log("开始获取所有特征值");
      this.ble.discoverCharacteristics({
        peripheralUUID: deviceId,
        serviceUUID: serviceId,
      }, (res, err) => {
        if (res.status) {
          console.log("已获取到特征值列表");
          this.characteristicsData = res.characteristics;
          this.characteristicsId = res.characteristics.find(res => res.properties == "notify").uuid;
          this.setNotify();
        } else {
          switch (err.code) {
          case 3:
            console.log("未找到指定服务");
            break;
          case 1:
            console.log("peripheralUUID 为空");
            break;
          case 2:
            console.log("serviceUUID 为空");
            break;
          case -1:
            console.log("未知错误");
            console.log("开始重新搜索特征值");
            this.discoverCharacteristics();
            break;
          case 4:
            console.log("尚未搜索到该蓝牙设备");
            console.log("开始重新搜索特征值");
            this.discoverCharacteristics();
            break;
          }
        }
      });
    },
    /**
     * 监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接，设备丢失，连接异常断开等等
     */
    setNotify() {

      this.setSearchingStatus(0);
      this.setWatchingStatus(1);

      let {deviceId, serviceId, characteristicsId} = this;
      console.log("开始监听数据");
      Toast("已经开始监听数据");
      this.startRecord();
      this.ble.setNotify({
        peripheralUUID: deviceId,
        serviceUUID: serviceId,
        characteristicUUID: characteristicsId,
      }, (res, err) => {
        // console.log(res);
        if (res.status) {
          var value = res.characteristic.value;
          var wendu = getTemperatureAndPower(value);
          this.temperature = wendu.temperature;
        } else {
          switch (err.code) {
          case 3:
            console.log("characteristicUUID 为空");
            break;
          case 1:
            console.log("peripheralUUID 为空");
            break;
          case 2:
            console.log("serviceUUID 为空");
            break;
          case -1:
            console.log("未知错误");
            console.log("开始重新监听特征值");
            this.setNotify();
            break;
          case 4:
            console.log("未找到指定特征（characteristic）");
            break;
          case 5:
            console.log("未找到指定服务（service）");
            break;
          case 6:
            console.log("尚未搜索到该蓝牙设备");
            break;
          }
          // console.log("err.code", err.code);
        }
      });
    },
    /**
       * 停止监听通知
       */
    onStopNotify() {
      this.setWatchingStatus(0);
      this.ble.stopNotify();
    },
    stopRecord(){
      if(this.recordInterval){
        console.log("停止记录");
        clearInterval(this.recordInterval);
        this.setRecordingStatus(0);
        this.recordInterval = null;
      }
    },
    startRecord(){
      if(!this.recordInterval){
        console.log("开始记录");
        this.setRecordingStatus(1);
        console.log("this.isRecording",this.isRecording);
        this.recordInterval = recordIntervalFunc(this);
      }
    },
    getstatus(){
      console.log(this.isRecording);
    },
    ...common.methods,
    ...mapMutations(["setRecordingStatus","setSearchingStatus","setWatchingStatus","setConnetedStatus","setScanStatus"]),
  },
};


function buffer2hex(value) {
  var t = "";
  if (value) {
    var v = new Uint8Array(value);
    for (var i in v) {
      t += "" + v[i].toString(16);
    }
  } else {
    t = "";
  }
  return t;
}

function getTemperatureAndPower(value) {
  var arr = value.split("");
  var b = arr.filter((value, index) => index % 2 === 1).join("");
  console.log("new temperature:" + b);
  var temperature = b.slice(0,2) + "." + b.slice(2,4);
  var power = b.slice(4,5);
  return {temperature,power};
}

async function storageLocal(temperature) {
  let [time,day] = dayjs().format("HH:mm:ss YYYY-MM-DD").split(" ");
  try{
    const r = await common.methods.writeFile({
      path:`cache://blewendu_${day}.log`,
      data:`@${time} ${temperature}`,
      append:true,
    });
    if(r.status){
      console.log(`已经写入日志文件：blewendu_${day}.log`);
    }
  }catch (e) {
    console.log(e);
  }
}

async function storageRemote(temperature){
  let res;
  try {
    res = await apiPostFetch("/api/temperatures/contents_submit",{temperature, id:2});

    console.log(res);
  }catch (e) {
    res = {
      status:-1,
      message:e,
    };
  }
  console.log(res);
}

function recordIntervalFunc(obj) {
  return setInterval(()=>{
    if(obj.temperature){
      //本低存储
      storageLocal(obj.temperature);

      //网络存储
      storageRemote(obj.temperature);
    }
  },2000);
}

</script>


<style lang="scss">

  @import "../../assets/style/var.scss";

  body{
    background: $index-bg;
  }

  section{
    color: $default-bgc;
    .img,.title {
      display: flex;
      flex-flow: row nowrap;
      justify-content: center;
      align-items: center;
    }
    .title{
      height: 80px;
    }
    .img{
      height: 320px;
    }
    .btn{
      font-size: 13px;
      height: 160px;
      display: flex;
      flex-flow: column nowrap;
      justify-content: space-around;
      align-items: center;
      span{
        color:$default-bgc;
      }
    }
    .van-button{
      background: $index-bg;
      width: 140px;
    }
  }

  </style>
